package com.springboot.handler;

import com.springboot.exception.MyException;
import com.springboot.utils.Response;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
*@descrition 统一异常处理
*@author lzh
*/
@ControllerAdvice
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)

    public Response handle(Exception e) {
        if (e instanceof MyException) {
            MyException myException = (MyException)e;
            return Response.error(myException.getCode(), myException.getMessage());
        } else if (e instanceof BindException) {
            BindException bindException = (BindException)e;
            return Response.error(bindException.getFieldError().getDefaultMessage());
        }
        e.printStackTrace();
        return Response.error(e.getMessage());
    }

}